<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/7/31
 * Time: 9:08
 */

namespace App\Utils;


class SimpleCaches
{
    private static $data = [];

    public static function set($key, $value, $ttl = 0)
    {
        $object = ["key" => $key, "value" => $value, "ttl" => $ttl, "createTime" => time()];
        self::$data[$key] = $object;
    }

    public static function get($key)
    {
        if (array_key_exists($key, SimpleCaches::$data)) {
            $object = self::$data[$key];
            if (self::timeout($object)) {
                self::remove($key);
                return null;
            } else {
                return $object["value"];
            }
        }
        return null;
    }

    public static function remove($key)
    {
        unset(self::$data[$key]);
    }

    public static function clearTimeoutCaches()
    {
        $keys = array_keys(self::$data);
        foreach ($keys as $key) {
            $object = self::get($key);
        }
    }

    private static function timeout($object)
    {
        if ($object["ttl"] <= 0) {
            return false;
        }
        $interval = time() - $object["createTime"];
        return $interval >= $object["ttl"];
    }

}


